package com.ruoyi.bmxt.service.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import com.ruoyi.bmxt.domain.BmFiles;
import com.ruoyi.bmxt.domain.BmSchoolLevel;
import com.ruoyi.bmxt.domain.BmSpecialtyFee;
import com.ruoyi.bmxt.domain.ui.FileZipDto;
import com.ruoyi.bmxt.service.IBmFilesService;
import com.ruoyi.bmxt.service.IBmSchoolLevelService;
import com.ruoyi.bmxt.service.IBmSpecialtyFeeService;
import com.ruoyi.bmxt.utils.LoginUserUtils;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.DownZipUtil;
import com.ruoyi.common.utils.file.DownZipUtilNew;
import com.ruoyi.common.utils.file.MyUploadUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.bmxt.mapper.BmStudentMapper;
import com.ruoyi.bmxt.domain.BmStudent;
import com.ruoyi.bmxt.service.IBmStudentService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 学生管理Service业务层处理
 *
 * @author 魏建波
 * @date 2023-02-24
 */
@Service
public class BmStudentServiceImpl implements IBmStudentService
{
    @Autowired
    private BmStudentMapper bmStudentMapper;

    @Autowired
    private IBmSchoolLevelService bmSchoolLevelService;

    @Autowired
    private IBmSpecialtyFeeService bmSpecialtyFeeService;

    @Autowired
    private IBmFilesService bmFilesService;

    @Autowired
    private RuoYiConfig ruoYiConfig;

    @Resource
    private SysDeptMapper deptMapper;

    @Resource
    ISysDeptService sysDeptService;

    /**
     * 查询学生管理
     *
     * @param studentId 学生管理主键
     * @return 学生管理
     */
    @Override
    public BmStudent selectBmStudentByStudentId(Long studentId)
    {
        return bmStudentMapper.selectBmStudentByStudentId(studentId);
    }

    /**
     * 查询学生管理列表
     *
     * @param bmStudent 学生管理
     * @return 学生管理
     */
    @Override
    public List<BmStudent> selectBmStudentList(BmStudent bmStudent)
    {
        // 获得登录用户id
        SysUser user = LoginUserUtils.getLoginUser();
        bmStudent.setLoginUserId(user.getUserId());
        return bmStudentMapper.selectBmStudentList(bmStudent);
    }

    /**
     * 新增学生管理
     *
     * @param bmStudent 学生管理
     * @return 结果
     */
    @Override
    public int insertBmStudent(BmStudent bmStudent)
    {
        bmStudent.setCreateTime(DateUtils.getNowDate());
        return bmStudentMapper.insertBmStudent(bmStudent);
    }

    /**
     * 修改学生管理
     *
     * @param bmStudent 学生管理
     * @return 结果
     */
    @Override
    public int updateBmStudent(BmStudent bmStudent)
    {
        // 处理一下文件
        bmStudent.setUpdateTime(DateUtils.getNowDate());
        return bmStudentMapper.updateBmStudent(bmStudent);
    }

    /**
     * 批量删除学生管理
     *
     * @param studentIds 需要删除的学生管理主键
     * @return 结果
     */
    @Override
    public int deleteBmStudentByStudentIds(Long[] studentIds)
    {
        return bmStudentMapper.deleteBmStudentByStudentIds(studentIds);
    }

    /**
     * 删除学生管理信息
     *
     * @param studentId 学生管理主键
     * @return 结果
     */
    @Override
    public int deleteBmStudentByStudentId(Long studentId)
    {
        return bmStudentMapper.deleteBmStudentByStudentId(studentId);
    }

    @Override
    @Transactional
    public int insertBmStudentByWeb(BmStudent bmStudent) throws IOException, InvalidExtensionException {
        // 根据专业名称查询学校层次信息
        if(bmStudent.getRegisterSchoolProfessionId()!=null && bmStudent.getRegisterSchoolProfessionId() != 0){
            // 根据专业id查专业费用信息
            BmSpecialtyFee specialtyFee = bmSpecialtyFeeService.selectBmSpecialtyFeeBySpecialtyFeeId(bmStudent.getRegisterSchoolProfessionId());
            // 根据学习层次id查学校级别信息
            BmSchoolLevel schoolLevel = bmSchoolLevelService.selectBmSchoolLevelBySchoolLevelId(specialtyFee.getSchoolLevelId());
            // 保存学生基础数据
            bmStudent.setRegisterSchoolId(schoolLevel.getSchoolId());
            bmStudent.setRegisterSchoolLevelId(schoolLevel.getLevelId());
            bmStudent.setFee(specialtyFee.getFee()); // 设置学费
            bmStudent.setRegisterSchoolRequirement(specialtyFee.getRemark());
        }
        bmStudentMapper.insertBmStudent(bmStudent);
        System.out.println("插入的学生id="+bmStudent.getStudentId());
        // 存储文件资料   id有了  把资料存储起来
        // 存储证件照片
        MultipartFile[] certificateFile = bmStudent.getCertificateFile();
        if(certificateFile !=null && certificateFile.length>0){
            for(MultipartFile file:certificateFile){
                String path = MyUploadUtils.upload(file, RuoYiConfig.getSignUpMaterialsPath()+"/"+bmStudent.getStudentId()+"/certificate"); // 证件照
                // 存储起来
                BmFiles bmFiles = new BmFiles();
                bmFiles.setFilePath(path);
                bmFiles.setFileTypeId("1"); //证件照
                bmFiles.setStudentId(bmStudent.getStudentId());
                bmFilesService.insertBmFiles(bmFiles);
            }
        }
        // 存储身份证正面
        MultipartFile[] idCardFrontFile = bmStudent.getIdCardFrontFile();
        if(idCardFrontFile !=null && idCardFrontFile.length>0){
            for(MultipartFile file:idCardFrontFile){
                String path = MyUploadUtils.upload(file, RuoYiConfig.getSignUpMaterialsPath()+"/"+bmStudent.getStudentId()+"/idCardFront"); // 身份证正面
                // 存储起来
                BmFiles bmFiles = new BmFiles();
                bmFiles.setFilePath(path);
                bmFiles.setFileTypeId("2"); //身份证正面
                bmFiles.setStudentId(bmStudent.getStudentId());
                bmFilesService.insertBmFiles(bmFiles);
            }
        }
        // 存储身份证反面
        MultipartFile[] idCardVersoFile = bmStudent.getIdCardVersoFile();
        if(idCardVersoFile !=null && idCardVersoFile.length>0){
            for(MultipartFile file:idCardVersoFile){
                String path = MyUploadUtils.upload(file, RuoYiConfig.getSignUpMaterialsPath()+"/"+bmStudent.getStudentId()+"/idCardVerso"); // 身份证反面
                // 存储起来
                BmFiles bmFiles = new BmFiles();
                bmFiles.setFilePath(path);
                bmFiles.setFileTypeId("3"); //身份证反面
                bmFiles.setStudentId(bmStudent.getStudentId());
                bmFilesService.insertBmFiles(bmFiles);
            }
        }
        // 前置学历照片
        MultipartFile[] highSchoolCertificateFile = bmStudent.getHighSchoolCertificateFile();
        if(highSchoolCertificateFile !=null && highSchoolCertificateFile.length>0){
            for(MultipartFile file : highSchoolCertificateFile){
                String path = MyUploadUtils.upload(file, RuoYiConfig.getSignUpMaterialsPath()+"/"+bmStudent.getStudentId()+"/highSchoolCertificate"); // 身份证反面
                // 存储起来
                BmFiles bmFiles = new BmFiles();
                bmFiles.setFilePath(path);
                bmFiles.setFileTypeId("4"); //毕业证
                bmFiles.setStudentId(bmStudent.getStudentId());
                bmFilesService.insertBmFiles(bmFiles);
            }
        }
        // 证明材料照片
        MultipartFile[] evidentiaryMaterialFiles = bmStudent.getEvidentiaryMaterialFiles();
        if(evidentiaryMaterialFiles !=null && evidentiaryMaterialFiles.length>0){
            for(MultipartFile file : evidentiaryMaterialFiles){
                String path = MyUploadUtils.upload(file, RuoYiConfig.getSignUpMaterialsPath()+"/"+bmStudent.getStudentId()+"/evidentiaryMaterial"); // 证明材料
                // 存储起来
                BmFiles bmFiles = new BmFiles();
                bmFiles.setFilePath(path);
                bmFiles.setFileTypeId("5"); //证明材料
                bmFiles.setStudentId(bmStudent.getStudentId());
                bmFilesService.insertBmFiles(bmFiles);
            }
        }
        return 1;
    }

    @Override
    public String checkIdCardUnique(BmStudent bmStudent) {
        BmStudent dbStudent = bmStudentMapper.checkIdCardUnique(bmStudent);
        if(dbStudent!=null){
            BeanUtils.copyProperties(dbStudent,bmStudent);
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
    @Override
    public String createFileByUser(FileZipDto fileZipDto)throws Exception {
        int copyFileCount = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//HHmmss
        String downloadName = sdf.format(new Date());
        // 先删除本地文件URLEncoder.encode(downloadName, "UTF-8")
        String tempPath = ruoYiConfig.getTempPath()+File.separator+"学生资料-"+downloadName;
        File zipDirectory = new File(tempPath); // D:\ruoyi2
        List<Map<String,Object>> userList = bmStudentMapper.createFileByUser(fileZipDto.getUserId());
        Map<Long,String> mapTemp = new HashMap<>();
        //循环一遍确认那些代理目录
        for(Map<String,Object> map : userList){
            mapTemp.put(Long.parseLong(String.valueOf(map.get("user_id"))),"代理"+map.get("user_id")+"_"+"_"+map.get("nick_name"));
        }
        //如果当前user的parentId，能在map中找到值，证明当前user是子级，重新封装路径放回map中
        for(Map<String,Object> map : userList){
            long parentId = Long.parseLong(String.valueOf(map.get("parent_id")));
            if(StringUtils.isNotBlank(mapTemp.get(parentId))){
                String filePath = mapTemp.get(parentId)+File.separator+"代理"+map.get("user_id")+"_"+map.get("nick_name");
                mapTemp.put(Long.parseLong(String.valueOf(map.get("user_id"))),filePath);
            }else{
                String filePath = "代理"+map.get("user_id")+"_"+map.get("nick_name");
                mapTemp.put(Long.parseLong(String.valueOf(map.get("user_id"))),filePath);
            }
        }
        //第三个循环开始复制文件
        for (Long key : mapTemp.keySet()) {
            FileZipDto fileZipDto1 = new FileZipDto();
            BeanUtils.copyProperties(fileZipDto,fileZipDto1);
            fileZipDto1.setUserId(key);
            List<Map<String,Object>> studentList = bmStudentMapper.queryStudentAndFile(fileZipDto1);
            if(studentList == null || studentList.size() == 0){
                continue;
            }
            for(Map<String,Object> stu : studentList){
                String directoryPath = tempPath+File.separator+mapTemp.get(key)+File.separator+"学生"+stu.get("student_id")+"_"+stu.get("student_name");
                File descDirectory = new File(directoryPath);
                if (!descDirectory.exists()){
                    //创建文件夹
                    if (descDirectory.mkdirs()){
                        System.out.println("《--------------------创建成功--------------------》");
                    } else {
                        System.out.println("《--------------------创建失败--------------------》");
                        return "目录创建失败,ps:"+stu.toString();
                    }
                }
                if(stu.get("file_path") != null){
                    String filePath = stu.get("file_path").toString();
                    String fileFullPath = RuoYiConfig.getProfile()+filePath.replace(Constants.RESOURCE_PREFIX,"");  // Constants.RESOURCE_PREFIX="/profile"
                    File srcFile = new File(fileFullPath);
                    if(! srcFile.exists()){
                        continue;
                    }
                    File descFile = new File(descDirectory,srcFile.getName());
                    System.out.println(descFile.getAbsolutePath());
                    Files.copy(srcFile.toPath(),descFile.toPath());
                    copyFileCount++;
                }
            }
        }
        if(copyFileCount > 0){
            // 删除所有文件
            DownZipUtilNew.zipFiles(tempPath,tempPath+".zip");
            DownZipUtil.deleteDirectory(zipDirectory); // 删除本地文件
        }
        return tempPath+".zip";
    }

    @Override
    public List<SysDept> selectDeptList(SysDept dept) {
        return deptMapper.selectDeptList(dept);
    }
    public void findNotChildList(List<SysDept> notChildList, SysDept dept){
        List<SysDept> children = dept.getChildren();
        if(children.size()==0){
            notChildList.add(dept);
        }else{
            // 遍历孩子
            for(SysDept d:children){
                findNotChildList(notChildList,d);
            }
        }
    }
    @Override
    public List<TreeSelect> buildDeptStaffTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = sysDeptService.buildDeptTree(depts);
        /*List<SysDept> notChildList = new ArrayList<>();
        // 遍历deptTrees  找到没有子节点的部门编号
        for(SysDept dept:deptTrees){
            findNotChildList(notChildList,dept);
        }
        // 获得
        SysUser user = LoginUserUtils.getLoginUser();
        for(SysDept notChild:notChildList){
            user.setDeptId(notChild.getDeptId());
            List<SysDept> children = bmStudentMapper.getDeptUserList(user);
            notChild.setChildren(children);
        }*/
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public BmStudent selectBmStudentByCardIdAndProjectId(String idCard,Long projectId) {
        BmStudent bmStudent = new BmStudent();
        bmStudent.setIdCard(idCard);
        bmStudent.setProjectId(projectId);
        return bmStudentMapper.selectBmStudentByCardId(bmStudent);
    }

}
